function findBraceEndIndex(s, begin) {
    var left = [],right = []
    for (var i = 0; i < s.length; i++) {
        if (s[i] === '[') left.push(i);
        if (s[i] === ']') right.push(i);
    }
    return right.reverse()[left.indexOf(begin)]
}
function interpreter(code, iterations, width, height) {
    code = code.replace(/[^\*nesw\[\]]/g, '')
    //initial mem
    var mem = Array.from({length:height},(_,k)=>Array.from({length:width},(_,i)=>0));
    var [p_row, p_col] = [0, 0];
    var loops = []
    for (var i = 0, j = 0; i < code.length && j < iterations; ++i, ++j) {
        switch (code[i]) {
            case '*':mem[p_row][p_col] ^= 1;break;
            case 'e':if (++p_col >= width) p_col = 0;break;
            case 'w':if (--p_col < 0) p_col = width - 1;break;
            case 'n':if (--p_row < 0) p_row = height - 1;break;
            case 's':if (++p_row >= height) p_row = 0;break;
            case '[':if (mem[p_row][p_col] != '0')loops.push(i);else i = findBraceEndIndex(code, i);break;
            case ']':if (mem[p_row][p_col] == '1')i = loops[loops.length - 1]; else loops.pop();break;
        }
    }
    return mem.map(v => v.join('')).join('\r\n')
}
